/* eslint  react/no-string-refs: 0 */
import React, { Component } from 'react';
import moment from 'moment';
import { Grid, Table } from '@alifd/next';
import { LineChart } from '#/components/Charts/';
import IceContainer from '@icedesign/container';
import '#/scss/Global.scss';
import axios from 'axios'
import creatHistory from 'history/createHashHistory' 
import { ApiOfResourceGet, ApiOfLatestMonitorData, ApiOfRealtimeMonitorData } from '#/utils/coreApiDefine'

const history = creatHistory();
const { Row, Col } = Grid;
export default class ChartView extends Component {
  static displayName = 'ChartView';

  static propTypes = {};

  static defaultProps = {};

  constructor(props) {
    super(props);
    this.state = {
      metricDefine: [],
      allLineChartData: [],
      lineChartDataLimit: 20,
      columnNum: 4,
      loadding: true
    };

    this.timeoutId = -1;
  }

  componentWillMount() {
    axios.all([
      ApiOfResourceGet(this.props.match.params.code), 
      ApiOfLatestMonitorData(this.props.match.params.code, this.state.lineChartDataLimit)
    ]).then(axios.spread( (response1, response2)=>{
      const data1 = response1.data;
      let metricDefine = []; 
      if(data1.metricGroupSize > 0 && data1.metricGroups.findIndex(it=> {return it.usageType == 'COLLECT' && it.metricSize > 0}) > -1) {
        metricDefine = data1.metricGroups.find(it=> it.usageType == 'COLLECT').metrics;
        metricDefine = metricDefine.filter(m=> m.valueCategory == 'ANALOG' || m.valueCategory == 'DIGITAL')
                    .map(m => {return {'code':m.code, 'name': m.name, 'valueCategory': m.valueCategory}});
      }

      const data2 = response2.data;
      data2.reverse();
      const allData = []
      metricDefine.forEach(md => {
        const oneData = {
          code: md.code,
          name: md.name,
          data: []
        }
        data2.forEach(d => {
          const json = JSON.parse(d.data);
          oneData.data.push({xAxis: moment(d.collectedTime).format('HH:mm:ss'), yAxis: json[md.code], field:md.name})
        })
        allData.push(oneData)
      })
     

      this.setState({
        metricDefine,
        allLineChartData: allData,
        loading: false
      })

      //this.loadRealtimeMonitorData(this.props.match.params.code);
    }))
  }

  componentWillUnmount() {
    clearTimeout(this.timeoutId)
  }

  loadRealtimeMonitorData(resouceCode) {
    const that = this;
    ApiOfRealtimeMonitorData(resouceCode).then(response => {
      const data = response.data;
      console.log(data)
      that.state.metricDefine.forEach(md => {
        const oneData = that.state.allLineChartData.find(it=>it.code == md.code)
        data.data.forEach(d => {
          oneData.data.push({xAxis: moment(d.collectedTime).format('HH:mm:ss'), yAxis: d[md.code], field:md.name})
        })
        //allData.push(oneData)
      })

      that.timeoutId = setTimeout(()=>{
        that.loadRealtimeMonitorData(resouceCode);
      }, 5 * 1000)
    })
  }

  onPlotDblClick(){
  }

  render() {

    const renderCharts = () => {
      const total = this.state.metricDefine.length;
      const columnNum = this.state.columnNum;
      const rowNum = Math.ceil(total / columnNum);
      const rows = []
      for(let i=0;i<rowNum;i++) {

        const columns = [];
        for(let j=i*columnNum;j<(i+1)*columnNum;j++) {
          if(j<total) {
            const dataItem = this.state.allLineChartData.find(it=>it.code == this.state.metricDefine[j].code)
            let data = [];
            if(dataItem) {
              data = dataItem.data;
            }
            const column = <Col l={24/columnNum} key={'chart-' + j}>
              <LineChart 
                data= {data} 
                xAxisVisible={true} 
                legendVisible={true} 
                height={200} />
            </Col>
            columns.push(column);
          }
        }
        const row = 
        <Row gutter="20" key={'row-' + i}>
          {columns}
        </Row>
        rows.push(row)
      }
     
      if(rows.length == 0 && this.state.loading === false) {
        return <IceContainer>
          <div style={styles.notfoundContent}>
            <img
              src={require('./images/TB1txw7bNrI8KJjy0FpXXb5hVXa-260-260.png')}
              style={styles.imgNotfound}
              alt="页面不存在"
            />
            <div className="prompt">
              <h3 style={styles.title}></h3>
              <p style={styles.description}>
                该设备没有可展示的数字量或模拟量数据，请返回<a href="#" onClick={()=>{history.goBack()}}>设备页</a>
              </p>
            </div>
          </div>
        </IceContainer>
      } else {
         return rows;
      }
    }
    
    return (
      <div className="chart-view">
        { renderCharts() }
      </div>
    );
  }
}

const styles = {
  notfoundContent: {
    display: 'flex',
    justifyContent: 'center',
    alignItems: 'center',
    minHeight: '500px',
  },
  imgNotfound: {
    marginRight: '50px',
  },
  title: {
    color: '#333',
    fontSize: '24px',
    margin: '20px 0',
  },
  description: {
    color: '#666',
    fontSize: '16px',
  },
};

